package com.jming.yygh.order.api;

import com.jming.yygh.common.result.Result;
import com.jming.yygh.order.service.PaymentService;
import com.jming.yygh.order.service.WeixinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author jming
 * @version 0.0.1
 * @date 2021/05/16
 */
@Api(tags = "微信支付接口")
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Resource
    private WeixinService weixinService;

    @Resource
    private PaymentService paymentService;

    /**
     * 根据订单id生成微信支付二维码
     *
     * @param orderId
     * @return Result
     */
    @ApiOperation("生成微信支付二维码")
    @GetMapping("createNative/{orderId}")
    public Result createNative(@PathVariable Long orderId) {

        return Result.ok(weixinService.createNative(orderId));
    }

    /**
     * 查询支付状态
     * @param orderId
     * @return Result
     */
    @ApiOperation(value = "查询支付状态")
    @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable Long orderId) {

        // 调用微信接口查询支付状态
        Map<String, String> resultMap = weixinService.queryPayStatus(orderId);

        // 支付判断
        if (null == resultMap) {
            return Result.fail().message("支付出错");
        }
        // 支付成功
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {
            // 更新状态
            String out_trade_no = resultMap.get("out_trade_no");
            paymentService.paySuccess(out_trade_no, resultMap);
            return Result.ok().message("支付成功");
        }

        return Result.ok().message("支付中");

    }


}
